#ifndef PATHDATAPARSER_H
#define PATHDATAPARSER_H

#include <QObject>
#include <QString>
#include <QVector>
#include <QSet>
#include <QPair>

#include <AlgManager/DataX.h>

class PathDataParser : public QObject
{
    Q_OBJECT

public:
    explicit PathDataParser(QObject *parent = nullptr);

    // 解析路径数据并返回指令集合（按气缸分组策略）
    QVector<QString> parsePathDataGrouped(const s_LzppRtsPara& pathResult);

    // 获取解析统计信息
    void getParseStats(int &totalPoints, int &totalCommands) const;

private:
    // 基础指令生成函数
    QString generateMoveCommand(const s_PPts& point);
    QString generateLiftCylinderCommand(const QSet<int>& cylinderIndexes);
    QString generatePutDownCylinderCommand(const QSet<int>& cylinderIndexes);
    QString generateLiftZCommand(double zHeight = 21.5);

    QString generateLiftGoBackCommand();

    // 分段下降相关函数
    void addSegmentedLowerZCommands(QVector<QString>& commands, double targetZHeight, int originalCNType);

    // 分组相关函数
    void createPathPointGroups(const std::vector<s_PPts>& pathPoints,
                               QVector<QPair<int, int>>& groups,
                               QVector<QSet<int>>& groupCylinders);
    void mergeEmptyCylinderGroups(const QVector<QPair<int, int>>& groups,
                                  const QVector<QSet<int>>& groupCylinders,
                                  QVector<QPair<int, int>>& finalGroups,
                                  QVector<QSet<int>>& finalCylinders);

    // 指令生成相关函数
    void processFirstGroup(QVector<QString>& commands,
                           const QSet<int>& currentCylinders,
                           double originalZHeight,
                           const s_PPts& firstPoint);
    void processGroupTransition(QVector<QString>& commands,
                                const QSet<int>& previousCylinders,
                                const QSet<int>& currentCylinders,
                                double originalZHeight,
                                int originalCNType);
    void processGroupMovement(QVector<QString>& commands,
                              const QPair<int, int>& group,
                              const std::vector<s_PPts>& pathPoints);
    void processFinalCommands(QVector<QString>& commands, const QSet<int>& lastCylinders);

    // 工具函数
    QSet<int> parseCylinderIndexes(const std::string& cylinderStr);
    QString cylinderIndexesToHex(const QSet<int>& cylinderIndexes);
    void debugOutputGroups(const QVector<QPair<int, int>>& groups,
                           const QVector<QSet<int>>& groupCylinders,
                           const std::vector<s_PPts>& pathPoints);

    void addLiftZIfNeeded(QVector<QString>& commands, double currentZ, double nextZ, int nextCNType);

    int m_totalPoints;
    int m_totalCommands;
};

#endif // PATHDATAPARSER_H
